package com.lbs.jiepiaisi.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.WeiZhangGaoFaDiBean;
import com.lbs.jiepiaisi.marker.Cluster.MarkerSign;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * 时间：2018/7/12 09:28
 * 作用：
 */
public class WeiZhangGaoFaDiAcitivity extends BaseActivity implements LocationSource {

    private MapView mapView;//地图
    private AMap aMap;//地图控制器对象
    private AMapLocationClient mLocationClient;
    private LocationSource.OnLocationChangedListener mListener;
    //定位的经纬度位置
    private LatLng locationLatLng;
    private ImageView mLocationIv;
    private Double lat,lon;
    private int num = 15;
    private int range = 2500;
    private Marker centerMarker;
    private List<Marker> markers = new ArrayList<>();
    private PopupWindow window;
    private View v, v2, v3;
    private TextView mTvContent, mTvAddress;
    private ImageView mIv, mIvClose;
    private View popupView;
    private int oloLength = 0;
    private int textLength = 0;
    private Marker oldMarker;
    private Bitmap b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate=true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weizhanggaofadi_layout);
        titleView.setText("违章高发地");

        mapView = (MapView) findViewById(R.id.map);
        v = findViewById(R.id.v);
        v2 = findViewById(R.id.v2);
        v3 = findViewById(R.id.v3);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        initView();
        initMap();
        initEvent();
    }

    private void initView() {
        mLocationIv = (ImageView) findViewById(R.id.btn_location);

    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        setUpMap();
    }

    private void initEvent() {
        mLocationIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ButtonUtil.isFastClick()){
                    try{
                        if(locationLatLng != null){
                            //poiOverlay.zoomToSpan();
                            moveMapToPosition(locationLatLng);
                        }
                    }catch (Exception e){

                    }
                }
            }
        });

        //地图移动监听事件
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                //centerMarker.setPositionNotUpdate(getMapCenterPoint());
                aMap.clear();
                addBlueMarker(cameraPosition.target);
                lat = cameraPosition.target.latitude;
                lon = cameraPosition.target.longitude;

                initData();
            }
        });

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(marker.getObject() != null){
                    if(oldMarker != null && b != null){
                        oldMarker.setIcon(BitmapDescriptorFactory.fromBitmap(b));
                    }
                    oldMarker = marker;
                    b = marker.getIcons().get(0).getBitmap();
                    if(b.getPixel(20, 10) == BitmapFactory
                            .decodeResource(getResources(),R.mipmap.green_weizhanggaofadi).getPixel(20, 10)){
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(),R.mipmap.green_weizhanggaofadimax)));
                    }
                    if(b.getPixel(20, 10) == BitmapFactory
                            .decodeResource(getResources(),R.mipmap.yellow_weizhanggaofadi).getPixel(20, 10)){
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(),R.mipmap.yellow_weizhanggaofadimax)));
                    }
                    if(b.getPixel(20, 10) == BitmapFactory
                            .decodeResource(getResources(),R.mipmap.red_weizhanggaofadi).getPixel(20, 10)){
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(),R.mipmap.red_weizhanggaofadimax)));
                    }

                    Log.e("dianjimarker","clickkkkk");
                    OpenWindow(marker.getTitle());
                    //window.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                    mTvContent.setText(marker.getTitle());
                    mTvAddress.setText(marker.getSnippet());
                }
                return true;
            }
        });

    }

    /**
     * by moos on 2018/01/12
     * func:移动地图视角到某个精确位置
     * @param latLng 坐标
     */
    private void moveMapToPosition(LatLng latLng) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(
                new CameraPosition(
                        latLng,//新的中心点坐标
                        16,    //新的缩放级别
                        0,     //俯仰角0°~45°（垂直与地图时为0）
                        0      //偏航角 0~360° (正北方为0)
                ));
        aMap.animateCamera(cameraUpdate, 300, new AMap.CancelableCallback() {
            @Override
            public void onFinish() {


            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void initData() {
        OkGo.<String>get(" http://jisuwzgfd.market.alicloudapi.com/illegaladdr/coord?lat=" + lat)
                .tag(this)
//                .headers("Host", "jisuwzgfd.market.alicloudapi.com")
//                .headers("X-Ca-Timestamp", "1531365730195")
//                .headers("gateway_channel", "http")
//                //.headers("X-Ca-Request-Mode", "debug")
//                .headers("X-Ca-Key", "24664361")
//                .headers("X-Ca-Stage", "RELEASE")
//                .headers("Content-Type", "application/json; charset=utf-8")
                .headers("Authorization", "APPCODE 8035f816dc954c4b8206b61058b53dd7")
                //.params("lat", lat + "")
                .params("lng", lon + "")
                .params("num", num + "")
                .params("range", range + "")
                .retryCount(3)
                .execute(new StringCallback(){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        if(response == null){
                            return;
                        }
                        if(response.body() == null){
                            return;
                        }

                        if(response.body().contains("\"resultView\":\"\"")){
                            return;
                        }
                        WeiZhangGaoFaDiBean o =  JSON.parseObject(response.body(), WeiZhangGaoFaDiBean.class);
                        final List<WeiZhangGaoFaDiBean.ResultBean> mData = o.result;
                        for(int i = 0; i<mData.size(); i++){
                            addMarker(new LatLng(mData.get(i).lat,
                                    mData.get(i).lng), mData.get(i));
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        super.onError(response);
                    }
                });

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    private void setUpMap() {
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    //aMap.moveCamera(CameraUpdateFactory.zoomTo(currentZoom));
                    //aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    if (mListener != null && aMapLocation != null) {
                        if (aMapLocation.getErrorCode() == 0) {
                            // 显示我的位置
                            mListener.onLocationChanged(aMapLocation);
                            lat = aMapLocation.getLatitude();
                            lon = aMapLocation.getLongitude();
                            locationLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                            addBlueMarker(locationLatLng);
                            initData();
                        } else {
                            String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();

                        }
                    }
                }
            });
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        }
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.point4));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }
    //添加违章marker
    private void addMarker(LatLng latLng, WeiZhangGaoFaDiBean.ResultBean resultBean){
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        //markerOption.title("西安市").snippet("西安市：34.341568, 108.940174");
        markerOption.title(resultBean.content + "(累计" + resultBean.num + "次)").snippet(resultBean.address);


        markerOption.draggable(false);//设置Marker可拖动
        if(Integer.valueOf(resultBean.num) < 50){
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),R.mipmap.green_weizhanggaofadi)));
        }
        if( 50 <=Integer.valueOf(resultBean.num) && Integer.valueOf(resultBean.num) <= 100){
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),R.mipmap.yellow_weizhanggaofadi)));
        }
        if(Integer.valueOf(resultBean.num) > 100){
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),R.mipmap.red_weizhanggaofadi)));
        }

        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        Marker marker = aMap.addMarker(markerOption);
        marker.setObject(new MarkerSign(1));

    }

    //添加选中点marker
    private void addBlueMarker(LatLng latLng){
        MarkerOptions markerOption = new MarkerOptions();
        //markerOption.position(latLng);
        markerOption.title("").snippet("");
        markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.mipmap.blue_weizhanggaofadi)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        centerMarker = aMap.addMarker(markerOption);
        centerMarker.setToTop();
        int left = mapView.getLeft();
        int top = mapView.getTop();
        int right = mapView.getRight();
        int bottom = mapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mapView.getX() + (right - left) / 2);
        int y = (int) (mapView.getY() + (bottom - top) / 2);
        centerMarker.setPositionByPixels(x, y);
    }

    /**
     * by moos on 2017/09/05
     * func:获取屏幕中心的经纬度坐标
     * @return
     */
    public LatLng getMapCenterPoint() {
        int left = mapView.getLeft();
        int top = mapView.getTop();
        int right = mapView.getRight();
        int bottom = mapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mapView.getX() + (right - left) / 2);
        int y = (int) (mapView.getY() + (bottom - top) / 2);
        Projection projection = aMap.getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));
        return pt;
    }

    private void OpenWindow(String title) {
        if(popupView == null){
            popupView = LayoutInflater.from(this).inflate(R.layout.layout_open_view, null);
            window = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
            window.setOutsideTouchable(false);
            //window.setFocusable(false);
            window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
            //popupView.measure(0, 0);
            window.setAnimationStyle(R.style.anim_menu_bottombar);//设置动画样式
            //window.showAsDropDown(v);

            mTvContent = popupView.findViewById(R.id.tv_content);
            mTvAddress = popupView.findViewById(R.id.tv_address);
            mIvClose = popupView.findViewById(R.id.iv_close);
            mIvClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                }
            });

            //window.setOnDismissListener(this);
        }else {
            //window.showAsDropDown(v);
        }
        if(title.length() < 18){
            window.dismiss();
            window.showAsDropDown(v);
        }
        if( 18 <= title.length() && title.length() <= 36){
            window.dismiss();
            window.showAsDropDown(v2);
        }
        if( 48 <= title.length()){
            window.dismiss();
            window.showAsDropDown(v3);
        }
    }

}
